<template>
    <div class="page-body" ref="pageRef">
        <e-form
            ref="ruleFormRef"
            :labelWidth="isMobanEdit ? '' : '0px'"
            :formConfig="formConfig"
            :formRule="rules"
            :formData="formData"
        >
            <template slot="bn_content">
                <div class="flex-wrap">
                    <div class="left" ref="leftRef">
                        <preview_bn
                            :name="formData.moban_component_code"
                            :isEdit="false"
                            :config="formData.bn_content"
                            @update="update"
                        />
                    </div>

                    <div class="right m-l-30 flex-1" v-if="!isLoading">
                        <div class="flex-wrap">
                            <el-button type="primary" @click="openDialog">选择组件</el-button>
                            <el-button type="primary" @click="download">生成pdf并下载</el-button>
                            <el-button v-if="isAdmin" type="primary" @click="openloadPage"
                                >openloadPage</el-button
                            >
                            <el-button type="primary" @click="openDialog1">使用说明</el-button>
                        </div>

                        <p class="f-14 l-h-20 c-danger m-t-20">
                            1、可拖动下面组件名排序 <br />
                            2、 点击简历分区，即可编辑对应区域内容<br />
                            <span v-if="isMobanEdit">
                                3、必须先输入模板code,才知道要使用哪个模板来渲染
                            </span>
                        </p>
                        <!-- 已选择组件 -->
                        <vuedraggable
                            class="m-t-20"
                            v-model="formData.bn_content.list"
                            filter=".forbid"
                            @end="onEnd"
                        >
                            <transition-group>
                                <div
                                    :class="[
                                        'flex-center-wrap m-b-10 w-300',
                                        isFixedSelect(item) ? 'forbid' : 'd-item-hover',
                                    ]"
                                    v-for="(item, index) in formData.bn_content.list"
                                    :key="index"
                                >
                                    <div class="flex-1">
                                        <kl-max-ell
                                            :text="getMobanName(item)"
                                            :ell="1"
                                            :lineHeight="19"
                                        />
                                    </div>
                                    <eSwitch
                                        successText="显示"
                                        errorText="隐藏"
                                        v-model="item.is_show"
                                        @change="(val) => changeSwitch(item)"
                                    />
                                    <el-button class="m-l-30" type="danger" @click="del(index)"
                                        >del</el-button
                                    >
                                </div>
                            </transition-group>
                        </vuedraggable>

                        <div class="flex-center-wrap m-t-20">
                            <el-button type="info" @click="cancel">返 回</el-button>
                            <el-button
                                type="primary"
                                @click="submit"
                                v-if="isMobanEdit && !formData._id"
                                >确定</el-button
                            >
                        </div>
                    </div>
                </div>
            </template>
        </e-form>

        <!-- 选择一级组件弹窗 -->
        <e-dialog v-model="visable" :footer="false" title="模板选择" width="900px">
            <div class="p-20 p-b-0">
                <div
                    :class="['pr', isFixedSelect(item) ? 'd-b-item' : '']"
                    v-for="(item, index) in list"
                    :key="index"
                    @click="select1(item)"
                >
                    <div v-if="item.component_type == 2" class="p-a p-a-html-item">固定模块</div>
                    <div :class="['fist-img']" v-html="item.component_html"></div>
                </div>
            </div>
        </e-dialog>
    </div>
</template>

<script>
// import klScroll from '@/mixins/components/kl-scroll/index.vue'
import eSwitch from '@/mixins/components/e-switch.vue'
export default {
    name: 'admin_bn_edit',
    components: {
        eSwitch,
        preview_bn: () => import('@/views/biographical_notes/components/preview_bn/index.vue'),
        'e-form': () => import('@/components/async/e-form.vue'),
        'kl-max-ell': () => import('@/components/async/kl-max-ell.vue'),
    },
    props: {
        isMobanEdit: {
            // 是否是后台页编辑
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            isLoading: true,
            formConfig: this.createFromConfig(),
            formData: {
                _id: '',
                moban_component_code: '',
                moban_component_name: '',
                bn_content: {
                    list: [],
                },
                moban_img_url: 'ceshi',
            },
            rules: {
                moban_component_code: [
                    { required: true, message: '请输入moban_component_code', trigger: 'blur' },
                ],
                moban_component_name: [
                    { required: true, message: '请选择moban_component_name', trigger: 'blur' },
                ],
                bn_content: [
                    // TODO: 这个校验为何不生效
                    {
                        validator: (rule, value, cb) => {
                            if (value.list.length === 0) {
                                return cb(new Error('未设置简历组件'))
                            }
                            cb()
                        },
                        trigger: 'change',
                    },
                ],
            },
            scrollHeight: 800,
            pageOption: {
                page: 1,
                limit: 10,
                total: 0,
            },
            list: [],
            visable: false,
        }
    },
    computed: {
        ...Vuex.mapState(['userdata']),
        ...Vuex.mapGetters(['isAdmin']),
        // 拉取详情的apikey
        detailsApiKey() {
            return this.isMobanEdit ? 'get_bn_moban' : 'get_bn_user'
        },
        postApiKey() {
            return this.isMobanEdit ? 'post_bn_moban' : 'post_bn_user'
        },
    },
    created() {
        this.getDetails()
    },
    mounted() {
        this.init()
    },
    methods: {
        changeSwitch(row) {
            const { row_code, is_show } = row || {}
            this.post_bn_partial_update('update', { info: row[row_code], is_show }).catch((err) => {
                this.getDetails()
                this.Toast(err)
            })
        },
        // 当前项是否是已经被选中的固定项
        isFixedSelect({ component_code, component_type }) {
            return this.formData.bn_content.list.some((item) => {
                return item.component_code == component_code && component_type == 2
            })
        },
        // 获取详情
        getDetails() {
            const { _id } = this.getQuery()
            // 获取详情
            if (_id) {
                this.$apis[this.detailsApiKey]({ _id }).then((res) => {
                    Object.assign(this.formData, res.data.data)
                    let { bn_content, bn_moban_id } = res.data.data
                    if (this.isObject(bn_moban_id)) {
                        Object.assign(this.formData, {
                            moban_component_code: bn_moban_id.moban_component_code,
                        })
                    }
                    bn_content.list = bn_content.list.map((item) => {
                        const { is_show } = item
                        // 只要不是隐藏，都是显示
                        if (!['1', '2'].includes(is_show)) {
                            this.$set(item, 'is_show', '1')
                        }
                        return item
                    })
                })
            }
        },
        download() {
            const params = {
                _id: this.getQuery()._id,
                type: this.isMobanEdit ? 'moban' : 'user',
            }
            this.$apis
                .post_create_pdf({
                    loading_msg: '简历生成中...',
                    user_id: this.userdata._id,
                    url: this.joinParams(`${location.origin}/#/create_pdf/${this.getQuery()._id}`, params),
                    ...params,
                })
                .then((res) => {
                    const { url } = res?.data || {}
                    if (!url) {
                        this.$message.error('简历生成失败')
                        return
                    }
                    window.open(this.$baseURL + url)
                })
                .catch((err) => {
                    this.Toast(err)
                })
        },

        download1() {
            const arr = []

            for (let i = 0; i < 2; i++) {
                arr.push(this.fun())
            }

            Promise.all(arr).then((res) => {
                console.log(res)
            })
        },
        openloadPage() {
            this.goTo(`/create_pdf/${this.getQuery()._id}`, {
                target: '_blank',
                query: {
                    _id: this.getQuery()._id,
                    type: this.isMobanEdit ? 'moban' : 'user',
                }
            })
        },
        async setHeight() {
            await this.sleep(30)
            const { leftRef, pageRef } = this.$refs
            if (!leftRef || !pageRef) {
                this.setHeight()
                return
            }

            // 获取到顶部的距离
            const { top } = leftRef.getBoundingClientRect()
            const { height } = this.getViewportSize()
            $(leftRef).css({
                height: height - top - 10 + 'px',
            })
        },
        init() {
            this.setHeight()
            this.getPlugins()
        },
        getPlugins() {
            // 判断是否已经挂载vuedraggable
            if (window.vuedraggable) {
                this.isLoading = false
                return
            }
            this.getIndexDBJS([
                {
                    js: 'http://47.108.195.190:5000/netdist/Sortablemin-1729685014570~1~.js',
                },
            ]).then(() => {
                this.getIndexDBJS([
                    {
                        js: 'http://47.108.195.190:5000/netdist/vuedraggable-1729685021040~1~.js',
                    },
                ]).then(() => {
                    this.isLoading = false
                    Vue.component('vuedraggable', window.vuedraggable)
                })
            })
        },
        createFromConfig() {
            let arr = [
                {
                    label: this.isMobanEdit ? '模板配置' : '',
                    type: 'customInput',
                    slot: 'bn_content',
                },
            ]

            if (this.isMobanEdit) {
                let arr1 = [
                    {
                        label: '模板code',
                        type: 'select',
                        modelName: 'moban_component_code',
                        className: 'w-300',
                        tip: '模板code就是，当前模板简历在preview_bn组件下的注册名字，必须保持一致',
                        options: [
                            {
                                label: 'classicStyleOne',
                                value: 'classicStyleOne',
                            },
                        ],
                    },
                    {
                        label: '模板名字',
                        type: 'input',
                        modelName: 'moban_component_name',
                        className: 'w-300',
                        tip: '1、只是用来搜索用的  2、用于模板选择展示',
                    },
                ]
                arr = [...arr1, ...arr]
            }
            return arr
        },
        async submit() {
            const res1 = await this.$refs.ruleFormRef.validateFn()
            if (!res1) return
            this.$apis[this.postApiKey](this.formData).then((res) => {
                this.updateUrl('_id', res.data._id)
                Object.assign(this.formData, res.data)
                this.$message.success(res.msg)
            })
        },
        bottom() {},
        get_first_stages() {
            const { page, limit } = this.pageOption
            const params = {}

            const key = this.isMobanEdit ? 'get_first_stages' : 'get_moban_first_stages'
            if (!this.isMobanEdit) {
                params.moban_id = this.formData?.bn_moban_id?._id
            } else {
                Object.assign(params, {
                    page,
                    limit,
                })
            }
            this.$apis[key](params).then((res) => {
                this.list = res?.data?.list || []
            })
        },
        openDialog() {
            const { moban_component_code } = this.formData
            if (!moban_component_code) {
                return this.$message.warning('请先选择模板')
            }
            this.visable = true

            this.get_first_stages()
        },
        async select1(row) {
            if (this.isFixedSelect(row)) return
            const row_code = this.createId()
            const rowCopy = this.deepCopy(row)
            delete rowCopy.component_html
            delete rowCopy.component_str
            const obj = {
                ...rowCopy,
                row_code,
                [row_code]: {
                    row_code,
                    // 标识是否需要用默认值，需要在更新的时候删除
                    is_need_default: true,
                },
                is_show: '1',
            }
            if (row.component_type == 2) {
                this.formData.bn_content.list.unshift(obj)
            } else {
                this.formData.bn_content.list.push(obj)
            }

            this.visable = false
            // 等待默认值更新
            await this.sleep(100)
            const obj1 = this.deepCopy(obj)
            // 需要移除is_need_default字段，如果用户后续一直没有更新，就会导致，组件默认值改了，用户的配置还是会使用默认值
            delete obj1[row_code].is_need_default

            this.post_bn_partial_update('add', { info: obj1 }).catch((err) => {
                this.getDetails()
                this.Toast(err)
            })
        },
        async update(row) {
            this.formData.bn_content.list = this.formData.bn_content.list.map((item) => {
                if (item.row_code === row.info.row_code) {
                    delete row.info.is_need_default
                    item[row.info.row_code] = this.deepCopy(row.info)
                }
                return item
            })
            this.post_bn_partial_update('update', { info: row.info || {} }).catch((err) => {
                this.getDetails()
                this.Toast(err)
            })
        },

        del(index) {
            let obj = this.formData.bn_content.list.splice(index, 1)
            this.post_bn_partial_update('del', {
                row_code: obj[0].row_code,
            }).catch((err) => {
                this.getDetails()
                this.Toast(err)
            })
        },
        cancel() {
            if (this.$route.name === 'biographical_notes_edit') {
                this.goTo(-1)
                return
            }
            this.updateUrl('_id', null)
            this.$emit('change', {
                page: 'list',
                reload: true,
            })
        },
        openDialog1() {
            this.$message.warning('开发中')
        },
        getMobanName(row) {
            const { row_code, component_type } = row
            if (component_type == 2) {
                return '固定项'
            }
            const { title, name } = row[row_code] || {}
            return title || name || '---'
        },
        onEnd(a, b) {
            const sort_row_codes = this.formData.bn_content.list.map((item) => item.row_code)
            this.post_bn_partial_update('sort', { sort_row_codes }).catch((err) => {
                this.getDetails()
                this.Toast(err)
            })
        },
        // 向服务端提交修改数据
        async post_bn_partial_update(handler_type, other = {}) {
            const { _id } = this.formData
            if (!_id) return
            // 局部更新
            await this.$apis.post_bn_partial_update({
                need_loading: false,
                _id,
                bn_type: this.isMobanEdit ? 1 : 2, // 1 模板 2 用户
                handler_type, // update 更新  del 删除 add 新增 sort 排序
                url: this.joinParams(`${location.origin}/#/create_pdf/${this.getQuery()._id}`, {
                    _id: this.getQuery()._id,
                    type: this.isMobanEdit ? 'moban' : 'user',
                }),
                ...other,
            })

            return true
        },
    },
}
</script>

<style lang="scss" scoped>
.page-body {
    overflow-y: auto;
    background-color: #f7f8fa;
}
.fist-img {
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
    padding: 10px;
}

.left {
    background-color: #fff;
    width: 820px;
    overflow-y: auto;
}
.p-a-html-item {
    left: 5px;
    top: 5px;
    padding: 6px 10px;
    background-color: rgba(0, 0, 0, 0.2);
    color: #fff;
}
.d-b-item {
    user-select: none;
    opacity: 0.5;
    cursor: not-allowed;
}
.d-item-hover {
    &:hover {
        background-color: #ccc;
    }
}
</style>
